# -*- encoding: utf-8 -*-
import time
import docker
import os
import datetime


def DockerStatusCheck():
    """
    容器监控服务
    1. Docker容器的状态,如果不是running状态,记录日志
    2. 容器进程的状态,如果不是R(running)状态,记录日志
    它使用docker.from_env()连接本地Docker服务,循环检查所有运行容器的状态。
    如果发现异常状态,会将日志记录到logs文件夹下,文件名为容器名称。
    """
    client = docker.from_env()
    # path = '/home/user/files'
    while True:
        for container in client.containers.list():
            print("docker ps -a:", client.containers.list())
            # 检查容器状态
            if container.status != 'running':
                log_path = f'/tmp/logs/'
                if not os.path.exists(log_path):
                    # 创建文件
                    os.makedirs(log_path)
                log_file = os.path.join(log_path, f'{container.name}.log')
                with open(log_file, 'w') as f:
                    f.write(container.status)
                # container.restart()  # 重启容器

            # 检查容器进程
            process = client.api.inspect_container(container.id)['State']['Pid']
            print("容器进程：", process)
            process_state = '/tmp/proc/'
            if not os.path.exists(process_state):
                os.makedirs(process_state)
            proc_file = os.path.join(process_state, f'{process}status.log')
            with open(proc_file, 'r') as f:
                status = f.readlines()
            for line in status:
                print("容器状态：", status)
                if 'State:' in line:
                    state = line.split(':')[1].strip().split(' ')[0]
                    if state != 'R':
                        log_path = f'/tmp/logs/'
                        if not os.path.exists(log_path):
                            os.makedirs(log_path)
                        log_file = os.path.join(log_path, f'{container.name}.log')
                        with open(log_file, 'w') as f:
                            f.write(f'Container halted. Process state: {state}')

        time.sleep(5 * 60)  # 每10秒检测一次


def removelog():
    days = 7
    path_name = '/tmp/logs'  # 输入要获取文件的根目录
    for filename in os.listdir(path_name):
        log_file = os.path.join('logs', filename)
        # 获取指定路径的状态
        if os.stat(log_file).st_mtime < (datetime.datetime.now() - datetime.timedelta(days=days)).timestamp():
            os.remove(log_file)


if __name__ == '__main__':
    DockerStatusCheck()
